package com.yvon.service.demo.spring.beans.factory.support;


import com.yvon.service.demo.spring.beans.BeansException;
import com.yvon.service.demo.spring.beans.factory.config.BeanDefinition;
import com.yvon.service.demo.spring.beans.factory.config.BeanPostProcessor;
import com.yvon.service.demo.spring.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象bean工厂类
 *
 * 继承了DefaultSingletonBeanRegistry所以也就具备了使用单例注册类方法
 * 实现BeanFactory，实现获取Bean的接口，先从单例注册表中获取，获取不到先获取BeanDefinition，在根据BeanDefinition创建bean
 * 获取BeanDefinition和根据BeanDefinition创建Bean定义为抽象方法，由子类自己实现和扩展
 * 运用模板模式定义了一个流程标准的用于获取对象的抽象类，屏蔽了内部实现细节
 *
 * 还存储了Bean后置处理器BeanPostProcessor，提供了添加和获取的方法
 *
 * @author Yvon
 * @since 2022-11-24
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    @Override
    public Object getBean(String name) {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) {
        return doGetBean(name, args);
    }

    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    protected <T> T doGetBean(String name, Object[] args) {
        Object bean = getSingleton(name);
        if (null != bean) {
            return (T) bean;
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T) createBean(name, beanDefinition, args);
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    /**
     * 获取bean定义
     *
     * @param beanName bean名字
     * @return {@code BeanDefinition }
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 创建bean
     *
     * @param beanName       bean名字
     * @param beanDefinition bean定义
     * @param args           args
     * @return {@code Object }
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
}
